package com.qfmy.service.impl.common;

import com.qfmy.service.novel.FileService;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author 清风明月
 * @Package com.qfmy.service.impl.common
 * @date 2025/6/11
 * @description 文件操作
 */
@Service
@SuppressWarnings("all")
public  class FileServiceImpl implements FileService {


    /**
     * pdf转word
     *
     * @param file
     * @return
     */
    @Override
    public ResponseEntity<byte[]> pdfToWord(MultipartFile file) {
        // 检查文件是否为空
        if (file == null || file.isEmpty()) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }

        try {
            // 加载 PDF 文件
            PDDocument pdDocument = PDDocument.load(file.getInputStream());
            // 创建 Word 文档
            XWPFDocument xwpfDocument = new XWPFDocument();
            // 提取 PDF 文本内容
            PDFTextStripper pdfTextStripper = new PDFTextStripper();
            String text = pdfTextStripper.getText(pdDocument);
            // 将文本写入 Word 文档
            XWPFParagraph paragraph = xwpfDocument.createParagraph();
            XWPFRun run = paragraph.createRun();
            run.setText(text);

            // 创建字节流来保存 Word 文档
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            xwpfDocument.write(byteArrayOutputStream);
            byteArrayOutputStream.close();
            pdDocument.close();
            xwpfDocument.close();

            // 获取字节数组
            byte[] wordBytes = byteArrayOutputStream.toByteArray();

            // 设置响应头和内容类型
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=converted.docx");
            headers.add(HttpHeaders.CONTENT_TYPE, "application/vnd.openxmlformats-officedocument.wordprocessingml.document");

            return new ResponseEntity<>(wordBytes, headers, HttpStatus.OK);

        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * pdf转文本
     *
     * @param file
     * @return
     */
    @Override
    public ResponseEntity<byte[]> pdfToText(MultipartFile file) {
        try (InputStream inputStream = file.getInputStream();
             PDDocument document = PDDocument.load(inputStream)) {
            // 使用 PDFTextStripper 提取文本
            PDFTextStripper pdfTextStripper = new PDFTextStripper();
            String text = pdfTextStripper.getText(document);

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=converted.txt");
            headers.add(HttpHeaders.CONTENT_TYPE, "text/plain; charset=UTF-8");

            // 将文本内容转换为字节数组
            byte[] textBytes = text.getBytes(StandardCharsets.UTF_8);

            // 返回 ResponseEntity
            return new ResponseEntity<>(textBytes, headers, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * pdf转excel
     *
     * @param file
     * @return
     */
    @Override
    public ResponseEntity<byte[]> pdfToExcel(MultipartFile file) {
        try (InputStream inputStream = file.getInputStream();
             PDDocument document = PDDocument.load(inputStream)) {
            // 使用 PDFTextStripper 提取文本
            PDFTextStripper pdfTextStripper = new PDFTextStripper();
            String text = pdfTextStripper.getText(document);

            // 创建一个新的 Excel 工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("PDF Content");

            // 将文本内容按行分割
            String[] lines = text.split("\\r?\\n");

            // 将每一行写入 Excel
            for (int i = 0; i < lines.length; i++) {
                Row row = sheet.createRow(i);
                Cell cell = row.createCell(0);
                cell.setCellValue(lines[i]);
            }

            // 将工作簿写入字节流
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            workbook.write(byteArrayOutputStream);
            byte[] excelBytes = byteArrayOutputStream.toByteArray();

            // 关闭资源
            byteArrayOutputStream.close();
            workbook.close();

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=converted.xlsx");
            headers.add(HttpHeaders.CONTENT_TYPE, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

            // 返回 ResponseEntity
            return new ResponseEntity<>(excelBytes, headers, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
